import { PokerHand } from "./PokerHand.js";
import { StraightThirdPokerHand } from "./StraightThirdPokerHand.js";
import { PokerCard } from "../PokerCard.js";
export type { PokerCard, PokerType } from "../PokerCard.js";

/** 最大连续次数以及相应的值 */
interface MaxTimeVal {
  /** 最大连续次数 */
  time: number;
  /** 最大值 */
  val: number;
}

/**
 * 获取三顺类型的最大连续数量
 * @param cards 手牌
 * @returns
 */
const getMaxContinuous = (cards: PokerCard[]): MaxTimeVal => {
  /** 临时对象 */
  const tmp: any = {};
  cards.forEach((card) => {
    if (tmp[card.value]) {
      tmp[card.value] += 1;
    } else {
      tmp[card.value] = 1;
    }
  });
  /** 三张牌以上的牌的数值 */
  const nums = Object.keys(tmp)
    // 三张牌
    .filter((key) => tmp[key] >= 3)
    // 转数字
    .map((v) => Number(v))
    // 不允许2
    .filter((v) => v <= 12)
    // 排序，从小到大
    .sort((a, b) => a - b);
  if (nums.length === 0) {
    return { time: 0, val: 0 };
  }
  /** 最大连续数量 */
  let max = 0;
  /** 最大连续数量对应的值 */
  let maxVal = 0;
  /** 当前连续数量 */
  let cur = 0;

  nums.forEach((n, i) => {
    if (i === 0) {
      cur = 1;
      max = 1;
      maxVal = n;
      return;
    }

    if (n - nums[i - 1] === 1) {
      cur += 1;
    } else {
      cur = 1;
    }

    if (max <= cur) {
      max = cur;
      maxVal = n;
    }
  });

  return { time: max, val: maxVal };
};

/** 三顺带单张 */
export class PlaneWithSinglePokerHand extends PokerHand {
  public value: number;
  constructor(cards: PokerCard[]) {
    super(cards);
    this.value = getMaxContinuous(cards).val;
  }

  /**
   * 判断是否飞机带翅膀(单)：三顺＋同数量的单牌。
   * @param cards 手牌
   * @returns
   */
  public static isStandard(cards: PokerCard[]) {
    const len = cards.length;

    // 少于8张牌
    if (len < 8 || len % 4 !== 0) {
      return false;
    }
    // 如果属于三顺的则排除
    if (StraightThirdPokerHand.isStandard(cards)) {
      return false;
    }

    return getMaxContinuous(cards).time >= len / 4;
  }
  public isStandard = PlaneWithSinglePokerHand.isStandard;
  public isBetter(target: PokerHand): boolean {
    if (target instanceof PlaneWithSinglePokerHand && target.cards.length === this.cards.length) {
      return this.value > target.value;
    }

    return false;
  }
}

export default PlaneWithSinglePokerHand;
